07. Exercise: Creating the SleepNight Entity

L6 09 Creating The NightData SC

Now it’s your turn to complete this exercise yourself.

In this step you'll be creating a data class to define the sleep data entity.

  1. In the database package, find and open the SleepNight.kt file.

  2. Create the SleepNight data class with parameters for an ID, start time and end time in milliseconds, and a numerical sleep quality rating:

  data class SleepNight  (
       var nightId: Long = 0L,
       val startTimeMilli: Long =  System.currentTimeMillis(),
       var endTimeMilli: Long = startTimeMilli,
       var sleepQuality: Int = -1
 )
  1. Annotate the data class with @Entity, and name the table daily_sleep_quality_table.

    (Remember to perform the necessary imports for this and all the following annotations.)

 @Entity(tableName = "daily_sleep_quality_table")
  1. Identify the nightId as the primary key by annotating it with @PrimaryKey, and set the autoGenerate parameter to true:

    @PrimaryKey(autoGenerate = true)

  2. Annotate the remaining properties with @ColumnInfo and customize their names as shown below.

    Your finished code should look like this:

@Entity(tableName = "daily_sleep_quality_table")
data class SleepNight(
       @PrimaryKey(autoGenerate = true)
       var nightId: Long = 0L,

       @ColumnInfo(name = "start_time_milli")
       val startTimeMilli: Long = System.currentTimeMillis(),

       @ColumnInfo(name = "end_time_milli")
       var endTimeMilli: Long = startTimeMilli,

       @ColumnInfo(name = "quality_rating")
       var sleepQuality: Int = -1
)
  1. Build and run your code to make sure it has no errors.

If you want to start at this step, you can download this exercise from: Step.01-Exercise-Create-Night-Data-Entity.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here: Step.01-Solution-Create-Night-Data-Entity, or using this git diff.

Task Description:

Complete these tasks to add a SleepNight entity to your app.

Task List:

Task Feedback:

Great! Now you're ready to create the Room database!